/* Clock in Hz */
#define F_CPU 8000000UL

#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

volatile uint8_t HR_COUNTER2; // High Register for Timer/Counter2
volatile uint16_t duty_cicle; // PWM duty cicle in us

ISR(TIMER2_OVF_vect) {

  HR_COUNTER2+=1;

}

ISR(PCINT1_vect) {

  if (bit_is_set(PINC,0)) {
    HR_COUNTER2 = 0;
    TCNT2 = 0;
  }
  else {
    duty_cicle = ((uint16_t) HR_COUNTER2 << 8) | TCNT2;
  }

}

void timer2_init(void){

  TCCR2B |= _BV(CS21); // 1/8 prescaler for 1MHz clock

  /* Enable Timer Overflow Interrupts */
  TIMSK2 |= _BV(TOIE2);

  /* Set High Register counter to 0 */
  HR_COUNTER2 = 0;
}

void set_pin_interrupt(void){
  
  PCICR |= _BV(PCIE1);
  PCMSK1 |= _BV(PCINT8);

}

void init_pwm(void) {

	TCCR1A = _BV(WGM11) |  _BV(COM1A1);
	TCCR1B = _BV(CS11) | _BV(WGM12) | _BV(WGM13); /* prescaler of 8, fast PWM */

        // 3456 is the servo center position
        OCR1A = 1500; /* 125 - 250 */
        ICR1 = 19999; // that evens out to 50hz

        DDRB = _BV(PB1); /* Set pin as output */
}

int main(void) {

  uint16_t pos;

  timer2_init();
  set_pin_interrupt();
  init_pwm();
  /* other set up */
  DDRC |= 1 << PC5;
  TCNT2 = 0;
  PORTC |= 1 << PC5;
  duty_cicle = 1500;

  /* Enable Interrupts */
  sei();
  
  while (1){
    pos = duty_cicle;
    OCR1A = pos;
    if (pos>=1500) {
      PORTC &= ~(1<<PC5);
    }
    else {
      PORTC |= 1 << PC5;
    }
  };

}
